package admin

import (
	"dario.cat/mergo"
	"gin-demo01/models"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type UserController struct {
}

func (u UserController) Index(c *gin.Context) {
	userList := []models.User{}

	models.DB.Find(&userList)

	c.JSON(http.StatusOK, gin.H{
		"code":   200,
		"result": userList,
	})
}

func (u UserController) GetById(c *gin.Context) {
	user := models.User{}

	models.DB.Where("id = ?", c.Param("id")).Find(&user)

	c.JSON(http.StatusOK, gin.H{
		"code":   200,
		"result": user,
	})
}

func (u UserController) Add(c *gin.Context) {
	user := models.User{}
	err := c.ShouldBind(&user)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"msg":     "创建失败",
		})
	}
	result := models.DB.Create(&user)
	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"msg":     "创建失败",
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"result":  user,
	})
}

func (u UserController) Edit(c *gin.Context) {
	user := models.User{Id: 3}
	user2 := models.User{}
	err := c.ShouldBind(&user2)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"msg":     "更新失败",
		})
	}
	models.DB.Find(&user)
	mergo.Merge(&user2, user)
	// 更新数据
	models.DB.Save(&user2)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"result":  user2,
	})
}

func (u UserController) Del(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"success": false,
				"msg":     "删除失败",
			})
		}
	}()
	n, _ := strconv.Atoi(c.Query("id"))
	user := models.User{
		Id: n,
	}
	models.DB.Delete(&user)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
	})
}
